package io.geekidea.boot.insurancePolicy.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.geekidea.boot.allocation.query.AllocationQuery;
import io.geekidea.boot.area.entity.ImportArea;
import io.geekidea.boot.area.query.AreaQuery;
import io.geekidea.boot.auth.util.LoginUtil;
import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.response.ApiResult;


import io.geekidea.boot.insurancePolicy.dto.*;

import io.geekidea.boot.insurancePolicy.entity.InsurancePolicyList;
import io.geekidea.boot.insurancePolicy.query.*;
import io.geekidea.boot.insurancePolicy.service.InsurancePolicyService;

import io.geekidea.boot.insurancePolicy.vo.NoguaranteeordersVo;
import io.geekidea.boot.insurancePolicy.vo.PersManagVo;
import io.geekidea.boot.insurancePolicy.vo.StoreWl;
import io.geekidea.boot.insurancePolicy.vo.VipVo;

import io.geekidea.boot.materials.entity.Materials;
import io.geekidea.boot.materials.service.MaterialsService;
import io.geekidea.boot.persmanag.dto.PersManagExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;import java.util.List;

@RestController
@RequestMapping("/bwd")
@Tag(name = "保外单接口")
public class InsurancePolicyController {
    @Resource
    private InsurancePolicyService insurancePolicyService;

    @Autowired
    private MaterialsService materialsService;


    @PostMapping("/updatebwd")
    @Operation(summary = "驳回后修改保外单")
    public ApiResult UpdateBwd(@RequestBody InsurancePolicyDto insurancePolicyDto){

//        QueryWrapper<InsurancePolicyList> queryWrapper = Wrappers.query();
//        queryWrapper.eq("id", insurancePolicyDto.get());

        InsurancePolicyList list=new InsurancePolicyList();
        BeanUtil.copyProperties(insurancePolicyDto,list);

        boolean update = insurancePolicyService.updateById(list);
        if (update){
            return ApiResult.success("修改保外单成功！",200);
        }else {
            return ApiResult.error("修改失败");
        }


    }



    @PostMapping ("/export")
    public void exportToExcel(@RequestBody  InsurancePolicyQuery insurancePolicyQuery , HttpServletResponse response) throws IOException {
// 查询数据
        List<InsuranceExcel> dataList = insurancePolicyService.getImport(insurancePolicyQuery);

        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String excelName = URLEncoder.encode("保外单"+ LocalDateTime.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
// 以字节流的形式输出响应正文
            outputStream = response.getOutputStream();
            try (ExcelWriter excelWriter = EasyExcel.write(outputStream, InsuranceExcel.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();


                excelWriter.write(dataList,writeSheet);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }


    }

    @PostMapping("/updatetotal")
    public ApiResult updateTotal(@RequestBody  UpdateTotalDto updateTotalDto){
        UpdateWrapper<Materials> wrapper = new UpdateWrapper<>();

        wrapper.eq("id",updateTotalDto.getId())
                .set("total_stock",updateTotalDto.getTotal_stock()).set("availableInventory",updateTotalDto.getAvailableInventory());
        boolean update = materialsService.update(null, wrapper);

        if (!update) {
            return ApiResult.success("修改失败",505);
        }
        return ApiResult.success("修改成功",200);
    }



    //修改
    @PostMapping("/update")

    public ApiResult updateAuditStatus(@RequestBody UpdateIpDto updateIpDto) {

        int row = insurancePolicyService.updateAuditStatus(updateIpDto);
        if (row!=0){
            return ApiResult.success("修改成功",200);
        }else {
            return ApiResult.error();
        }
    }

    //获得保外单类型
    @PostMapping("/getBwdType")
    @Operation(summary = "获得保外单类型")
    public ApiResult getBwd(){
        List<NoguaranteeordersVo> noguranteeorder = insurancePolicyService.getNoguranteeorder();
        return ApiResult.success(noguranteeorder);
    }

    //添加
    @PostMapping("/add")
    @Operation(summary = "添加保外单")
    public ApiResult addInsurancePolicy(@RequestBody InsurancePolicyDto insurancePolicyDto){

        insurancePolicyDto.setMakeOrderTime(LocalDateTime.now());

        int rows = insurancePolicyService.addinsurancePolicy(insurancePolicyDto);
        if (rows!=0){
            return ApiResult.success("新增成功",200);
        }else {
            return ApiResult.error();
        }
    }

    @PostMapping("/getvip")
    public ApiResult queryVip(@RequestBody VipQuery vipQuery){
        List<VipVo> vipList=insurancePolicyService.getVipList(vipQuery);
        return ApiResult.success(vipList);
    }

    @PostMapping("/getStoreWl")
    public ApiResult queryStoreWl(@RequestBody StoreWlQuery storeWlQuery){
        List<StoreWl> storeWlList=insurancePolicyService.getStoreWlList(storeWlQuery);
        return ApiResult.success(storeWlList);
    }
    @PostMapping("/getEngineer")
    public ApiResult queryEngineer(@RequestBody EngineerQuery engineerQuery){
        List<PersManagVo> engineerList = insurancePolicyService.getEngineerList(engineerQuery);
        return ApiResult.success(engineerList);
    }

    @PostMapping("/queryAll")
    @Operation(summary = "查询所有保外单")
    public ApiResult queryAll(@RequestBody InsurancePolicyQuery insurancePolicyQuery){
        Page<InsurancePolicyList> page = new Page<>(insurancePolicyQuery.getPage(), insurancePolicyQuery.getSize());
        Page<InsurancePolicyList> pageDto = insurancePolicyService.getInsurancePolicyList(page, insurancePolicyQuery);
        PageDto<InsurancePolicyList> pageInfo = new PageDto<>(pageDto.getRecords(),pageDto.getTotal(),pageDto.getSize(),pageDto.getCurrent());
        return ApiResult.success(pageInfo);
    }
}
